<template>
    <div class="department-container">
        <!-- 面包导航 -->
        <el-breadcrumb separator="/" style="padding-left: 10px; padding-bottom: 10px; font-size: 12px">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>系统管理</el-breadcrumb-item>
            <el-breadcrumb-item>部门管理</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card class="box-card">
            <!-- 搜素区域 -->
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input
                        size="small"
                        clearable
                        v-model="queryMap.name"
                        placeholder="请输入部门查询"
                        @clear="search"
                        class="input-with-select"
                    >
                        <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button
                        size="small"
                        v-hasPermission="'department:add'"
                        type="success"
                        icon="el-icon-circle-plus-outline"
                        @click="add"
                        >添加</el-button
                    >
                    <el-button
                        size="small"
                        v-hasPermission="'department:export'"
                        icon="el-icon-download"
                        @click="downExcel"
                        >导出</el-button
                    >
                </el-col>
            </el-row>

            <!-- 部门表格区域 -->
            <el-table
                border
                size="small"
                v-loading="loading"
                stripe
                :data="departmentData"
                style="width: 100%; margin-top: 20px"
                height="460"
            >
                <el-table-column prop="id" type="index" label="ID" width="50"></el-table-column>
                <el-table-column prop="phone" label="办公电话" width="180"></el-table-column>
                <el-table-column prop="name" label="部门名" width="120"></el-table-column>
                <el-table-column prop="total" label="人数" sortable width="100">
                    <template slot-scope="scope">
                        <el-tag effect="plain" v-text="scope.row.total + '人'" size="small"> </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" sortable></el-table-column>
                <el-table-column prop="modifiedTime" label="修改时间" sortable></el-table-column>
                <el-table-column prop="address" sortable label="地址"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button
                            v-hasPermission="'department:edit'"
                            size="mini"
                            icon="el-icon-edit-outline"
                            @click="edit(scope.row.id)"
                            >编辑</el-button
                        >

                        <el-button
                            v-hasPermission="'department:delete'"
                            type="danger"
                            size="mini"
                            icon="el-icon-delete"
                            @click="del(scope.row.id)"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页区域 -->
            <div class="pagination-container" style="margin: 10px 0; float: right">
                <el-pagination
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryMap.pageNum"
                    :page-sizes="[8, 16, 32, 64]"
                    :page-size="queryMap.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                ></el-pagination>
            </div>

            <!--   添加部门   -->
            <el-dialog title="添加部门" :visible.sync="addDialogVisible" width="40%" @close="closeAddDialog">
                <el-form :model="addForm" :rules="FormRoles" ref="addFormRef" label-width="100px" class="demo-ruleForm">
                    <el-form-item label="部门名称" prop="name">
                        <el-input v-model="addForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="办公电话" prop="phone">
                        <el-input v-model="addForm.phone"></el-input>
                    </el-form-item>
                    <el-form-item label="办公地址" prop="address">
                        <el-input type="textarea" v-model="addForm.address"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addDepartment">添 加</el-button>
                </span>
            </el-dialog>

            <!--   编辑部门   -->
            <el-dialog title="编辑部门" :visible.sync="editDialogVisible" width="40%" @close="closeEditDialog">
                <el-form
                    :model="editForm"
                    :rules="FormRoles"
                    ref="editFormRef"
                    label-width="100px"
                    class="demo-ruleForm"
                >
                    <el-form-item label="部门名称" prop="name">
                        <el-input v-model="editForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="办公电话" prop="phone">
                        <el-input v-model="editForm.phone"></el-input>
                    </el-form-item>
                    <el-form-item label="办公地址" prop="address">
                        <el-input type="textarea" v-model="editForm.address"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editDepartment">编 辑</el-button>
                </span>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
import axios from "axios";
export default {
    name: "Department",

    data() {
        const checkPhone = (rule, value, callback) => {
            const phoneReg = /^1[34578]\d{9}$$/;
            if (!value) {
                return callback(new Error("电话号码不能为空"));
            }
            setTimeout(() => {
                if (!Number.isInteger(+value)) {
                    callback(new Error("请输入数字值"));
                } else {
                    if (phoneReg.test(value)) {
                        callback();
                    } else {
                        callback(new Error("电话号码格式不正确"));
                    }
                }
            }, 100);
        };

        return {
            queryMap: { name: "", pageNum: 1, pageSize: 7 }, //查询条件
            addDialogVisible: false, //显示添加对话框
            editDialogVisible: false, //编辑对话框
            loading: false,
            total: 0,
            grantId: null, //需要授权的id
            departmentData: [
                {
                    id: 1,
                    phone: "1220",
                    name: "物资管理部门",
                    total: "10",
                    createTime: "2021-12-09",
                    modifiedTime: "2021-12-09",
                    address: "河南省郑州市",
                },
            ], //角色表格数据
            addForm: {
                name: "",
                phone: "",
                address: "",
            }, //添加数据
            editForm: {}, //编辑数据

            FormRoles: {
                name: [
                    { required: true, message: "请输入部门名称", trigger: "blur" },
                    { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" },
                ],
                address: [
                    { required: true, message: "请输入办公地址", trigger: "blur" },
                    { min: 4, max: 12, message: "长度在 4 到 12 个字符", trigger: "blur" },
                ],
                phone: [
                    {
                        validator: checkPhone,
                        trigger: "blur",
                    },
                ],
            }, //添加验证规则

            data: [], //菜单数据
            open: [], //默认打开节点的key集合
            defaultProps: {
                children: "children",
                label: "menuName",
            }, //基础变量配置
            //查询对象
        };
    },
    created() {
        this.loading = true;
        this.getDepartmentList();
        setTimeout(() => {
            this.loading = false;
        }, 500);
    },

    mounted() {},

    methods: {
        // 1. 加载部门别列表
        async getDepartmentList() {
            const { data: res } = await this.$http.get("department/findDepartmentList", { params: this.queryMap });
            // console.log(res);
            if (res.code == 200) {
                this.departmentData = res.data.rows;
                this.total = res.data.total;
            } else {
                return this.$message.error("获取部门列表失败!");
            }
        },

        // 2. 搜索
        search() {
            this.pageNum = 1;
            this.getDepartmentList();
        },

        // 导出Excel
        downExcel() {
            const that = this;
            const res = axios
                .request({
                    url: "department/excel",
                    method: "post",
                    responseType: "blob",
                })
                .then((res) => {
                    if (res.headers["content-type"] === "application/json") {
                        return that.$message.error("Subject does not have permission [role:export]");
                    }
                    const data = res.data;
                    let url = window.URL.createObjectURL(data); // 将二进制文件转化为可访问的url
                    const a = document.createElement("a");
                    document.body.appendChild(a);
                    a.href = url;
                    a.download = "部门列表.xls";
                    a.click();
                    window.URL.revokeObjectURL(url);
                });
        },

        //
        add() {
            this.addDialogVisible = true;
        },
        // 编辑按钮事件
        async edit(id) {
            const { data: res } = await this.$http.get("department/edit/" + id);
            if (res.code == 200) {
                // 部门数据回显
                this.editForm = res.data;
                this.editDialogVisible = true;
            } else {
                return this.$message.error("部门信息编辑失败!");
            }
        },

        // 3. 添加
        addDepartment() {
            this.$refs.addFormRef.validate(async (valid) => {
                if (valid) {
                    const { data: res } = await this.$http.post("department/add", this.addForm);
                    // console.log(res);
                    if (res.code == 200) {
                        this.$notify.success({
                            title: "操作成功",
                            message: "部门添加成功",
                        });
                        this.addForm = {};
                        this.addDialogVisible = false;
                        this.getDepartmentList();
                    }
                } else {
                    return this.$message.error("部门添加失败!");
                }
            });
        },

        // 4.修改部门
        editDepartment() {
            this.$refs.editFormRef.validate(async (valid) => {
                if (valid) {
                    const { data: res } = await this.$http.put("department/update/" + this.editForm.id, this.editForm);
                    if (res.code == 200) {
                        this.$notify({
                            title: "操作成功",
                            message: "部门基本信息已更新",
                            type: "success",
                        });
                        this.editForm = {};
                        this.getDepartmentList();
                        this.editDialogVisible = false;
                    }
                } else {
                    return this.$message.error("部门信息更新失败!");
                }
            });
        },

        // 5.修改部门
        del(id) {
            this.$confirm("此操作将永久删除该部门, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(async () => {
                    const { data: res } = await this.$http.delete("department/delete/" + id);
                    // console.log(res);
                    if (res.code == 200) {
                        this.$message({
                            type: "success",
                            message: "删除成功!",
                        });
                        this.getDepartmentList();
                    }
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除",
                    });
                });
        },

        // 关闭添加对话框
        closeAddDialog() {
            this.addDialogVisible = false;
            this.$refs.addFormRef.resetFields(); // 清空上次的校验
        },
        closeEditDialog() {
            this.editDialogVisible = false;
            this.$refs.editFormRef.resetFields(); // 清空上次的校验
        },

        //改变页码
        handleSizeChange(newSize) {
            this.queryMap.pageSize = newSize;
            this.getDepartmentList();
        },
        //翻页
        handleCurrentChange(current) {
            this.queryMap.pageNum = current;
            this.getDepartmentList();
        },
    },
};
</script>

<style lang="less" scoped></style>
